package session

import (
	"chat/lib/chat"
	"chat/lib/maskword"
	"chat/rpc"
	"encoding/json"
	"fmt"
	"strings"
	"time"
)

const (
	cmdPopular = "/popular"
	cmdStats   = "/stats"
	cmdDefault = ""
)

var cmdList = map[string]func(sess *Session, param string) ([]byte, error){
	cmdPopular: doCmdPopular,
	cmdStats:   doCmdStats,
	cmdDefault: doCmdChat,
}

func dispather(sess *Session, data []byte) (rst []byte, err error) {
	cmd, prama := parseCmd(string(data))
	if c, ok := cmdList[cmd]; ok {
		rst, err = c(sess, prama)
	}
	return
}

func parseCmd(s string) (c string, p string) {
	c = cmdDefault
	if !strings.HasPrefix(s, "/") {
		return
	}
	if strings.HasPrefix(s, cmdStats) {
		c = cmdStats
		return
	}
	if strings.HasPrefix(s, cmdPopular) {
		c = cmdPopular
		arr := strings.Split(s, " ")
		p = arr[1]
		return
	}
	return
}

func doCmdPopular(sess *Session, p string) ([]byte, error) {
	fmt.Println("doCmdPopular ", p)
	top1 := chat.Mgr.Top()

	return []byte(top1), nil
}

func doCmdStats(sess *Session, p string) ([]byte, error) {
	fmt.Println("doCmdStats ", p)
	user := Get(p)
	if user == nil {
		return nil, nil
	}
	e := time.Now().Sub(user.loginAt)
	str := fmt.Sprintf("%02fh %02fm %02fs", e.Hours(), e.Minutes(), e.Seconds())
	return []byte(str), nil
}

func doCmdChat(sess *Session, p string) ([]byte, error) {
	fmt.Println("doCmdChat ", p)
	//check words
	msg := []rune(p)
	star := []rune("*")[0]
	if terms := maskword.Search(msg); len(terms) > 0 {
		for _, v := range terms {
			for i := v.Pos; i < v.Pos+len(v.Word); i++ {
				msg[i] = star
			}
		}
	}
	var data = &chat.Message{
		From:   sess.ID,
		SendAt: time.Now().Unix(),
		Data:   p,
	}
	bin, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}
	rpc.ClientConn.Notify(bin)
	return nil, nil
}
